package org.example.domain.strategy.service.rule.chain.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.domain.strategy.service.armory.IStrategyDispatch;
import org.example.domain.strategy.service.rule.chain.AbstractLogicChain;
import org.example.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import org.example.types.common.Constants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.LoggingPermission;

/**
 * @Author: PengHao
 * @CreateTime: 2025-07-15  15:42
 * @Description: TODO
 */
@Slf4j
@Component("rule_weight")
public class RuleWeightLogicFilter extends AbstractLogicChain {
    @Resource
    private IStrategyRepository strategyRepository;
    @Resource
    private IStrategyDispatch strategyDispatch;

    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        log.info("抽奖责任链-权重开始 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());

        String ruleValue = strategyRepository.queryStrategyRuleValue(strategyId,ruleModel());
        if(ruleValue == null || ruleValue.isEmpty()){
            log.info("抽奖责任链-权重放行 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
            return next().logic(userId,strategyId);
        }

        //根据用户抽奖消耗的积分来判断奖池的类型  这里先写死为4500
        Map<Long, String> analyticalValue = getAnalyticalValue(ruleValue);//key是积分阈值，value是能够抽奖的奖品ID
        if(analyticalValue == null || analyticalValue.isEmpty()){
            return next().logic(userId,strategyId);
        }

        //用key值进行从大到小排序，方便查找
        ArrayList<Long> analyticalSortedKeys = new ArrayList<>(analyticalValue.keySet());
        Collections.reverse(analyticalSortedKeys);
        //查询用户使用次数
        Integer userScore = strategyRepository.queryActivityAccountTotalUseCount(userId,strategyId);

        //找出最小符合的值，也就是【4500 积分，能找到 4000:102,103,104,105】、【5000 积分，能找到 5000:102,103,104,105,106,107】
        Long nextValue = analyticalSortedKeys.stream()
                .filter(key -> userScore >= key)
                .findFirst()
                .orElse(null);
        if(nextValue!=null){
            Integer awardId = strategyDispatch.getRandomAwardId(strategyId,nextValue.toString());
            return DefaultChainFactory.StrategyAwardVO.builder()
                    .logicModel(ruleModel())
                    .awardId(awardId)
                    .build();
        }

        //过滤其他责任链
        log.info("抽奖责任链-权重放行 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
        return next().logic(userId,strategyId);

    }

    private Map<Long, String> getAnalyticalValue(String ruleValue) {
        String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
        Map<Long, String> ruleValueMap = new HashMap<>();
        for (String ruleValueKey : ruleValueGroups) {
            // 检查输入是否为空
            if (ruleValueKey == null || ruleValueKey.isEmpty()) {
                return ruleValueMap;
            }
            // 分割字符串以获取键和值
            String[] parts = ruleValueKey.split(Constants.COLON);
            if (parts.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueKey);
            }
            ruleValueMap.put(Long.parseLong(parts[0]), ruleValueKey);
        }
        return ruleValueMap;
    }

    @Override
    protected String ruleModel() {
        return DefaultChainFactory.LogicModel.RULE_WEIGHT.getCode();
    }
}
